define(
	[
		'require',
		'../../business/ctrls/detail_ctrl',
		'../../business/ctrls/center_ctrl'
	],
	function(require){
		var Controller = Ember.Controller.extend({
			needs: ["ServiceServerFollow","businessDetail","businessCenter"],

			business: Ember.computed.alias('controllers.businessDetail.model'),

			setup: function(model){
				this.set("isConfigIndicators", false);
				this.set("isCompareMode", false);
				this.set("model", model);
			},
			indicators: Ember.computed("model", function(key, value){
				if(arguments.length == 1){
					var ctrl = this;
					var asynArr = Ember.A();
					asynArr.isLoading = true;
					setTimeout(function(){
						ctrl.requireIndicators();
					});
					return asynArr;
				}else{
					Ember.A(value).forEach(function(item){
						item._checked = item.mode == 1;
						item._chartId = "node"+item.code+"View";
					});
					return value;
				}
			}),

			isCompareMode: false,

			modelChange: Ember.observer("model", "isCompareMode", function(){
				this.refreshData();
			}),

			indicatorCheckChange: Ember.observer("indicators.@each._checked", function(args){
				var checkIndictors = this.get("indicators").filterProperty('_checked', true),
					nodeId = this.get("model.id"),metricIds = [];
				checkIndictors.forEach(function(checkIndictor){
						metricIds.push(checkIndictor.metricId);
					});
				this.store.ajax("PUT", "node/indicators/"+nodeId+"/system", metricIds);
			}),

			requireIndicators: function(){
				var ctrl = this,
					nodeId = this.get("model.id");
				this.set("indicators.isLoading", true);
				return this.store.ajax("GET", "node/indicators",{
					"nodeId":nodeId,
					"panelId":"system"
				})
				.then(function(response){
					ctrl.set("indicators", Ember.A(response.indicatorConfig));
					ctrl.set("indicators.isLoading", false);
					return response;
				});
			},

			requirePerformances: function() {
				var ctrl = this,
					nodeId = this.get("model.id"),
					appPfms = this.get("business.performances"),
					store = this.store;
					var startDate, endDate = new Date(new Date() - timeD_value);
					endDate.setSeconds(0);
					endDate.setMilliseconds(0);
					startDate = new Date(+endDate);
					startDate.setHours(startDate.getHours()-1);
					if(!startDate&&!endDate){
						return;
					}
					pfmsCompletion = ctrl.get("performancesCompletion");
				return store.ajax("GET", "performances", {
					appIds: 'default',
					nodeIds: nodeId,
					startDate: +startDate,
					endDate: +endDate
				})
				.then(function(response){
					 var data = pfmsCompletion(Ember.A(response[nodeId]||[]), startDate, endDate);
					ctrl.set("performances", data);
				});
			},
			
			requireCompareData: function() {
				var ctrl = this,
					appId = 'default',
					nodeId = this.get("model.id"),
					appPfms = this.get("business.performances"),
					store = this.store;
					pfmsCompletion = ctrl.get("performancesCompletion");
				// if( !(appPfms && appPfms.length > 0) ){
				// 	return Ember.RSVP.reject("时序图没有数据");
				// }
				 var sDate, endDate = new Date(new Date() - timeD_value);
					endDate.setSeconds(0);
					endDate.setMilliseconds(0);
					sDate = new Date(+endDate);
					sDate.setHours(sDate.getHours()-1);
				var sDate0, eDate0, sDate1, eDate1, sDate2, eDate2;

				sDate0 =  new Date(sDate);
				eDate0 =  new Date(+sDate0);
				eDate0.setHours(eDate0.getHours()+1);

				sDate1 = new Date(sDate);
				sDate1.setDate(sDate1.getDate()-1);
				eDate1 = new Date(+sDate1);
				eDate1.setHours(eDate1.getHours()+1);

				sDate2 = new Date(sDate);
				sDate2.setDate(sDate2.getDate()-7);
				eDate2 = new Date(+sDate2);
				eDate2.setHours(eDate2.getHours()+1);

				return Ember.RSVP.all([
					store.ajax("GET", "performances", {
						appIds: appId,
						nodeIds: nodeId,
						startDate: +sDate0,
						endDate: +eDate0
					}),
					store.ajax("GET", "performances", {
						appIds: appId,
						nodeIds: nodeId,
						startDate: +sDate1,
						endDate: +eDate1
					}),
					store.ajax("GET", "performances", {
						appIds: appId,
						nodeIds: nodeId,
						startDate: +sDate2,
						endDate: +eDate2
					})
				])
				.then(function(response){
					var nodePerformances = [
						pfmsCompletion(Ember.A(response[2][nodeId]||[]), sDate2, eDate2,1),
						pfmsCompletion(Ember.A(response[1][nodeId]||[]), sDate1, eDate1,2),
						pfmsCompletion(Ember.A(response[0][nodeId]||[]), sDate0, eDate0,3)
					];
					ctrl.set("nodePerformances", nodePerformances);
				});
			},

			refreshData: function(){
				if(this.get("isCompareMode")){
					this.requireCompareData();
				}else{
					this.requirePerformances();
				}
			},
			/*
				启动实时模式
			*/
			startRealTimeMode: function(){
				_requireData(this);

				function _requireData(ctrl){
					interval = 60000;
					ctrl.timeTicket = setTimeout(function() {
						_requireData(ctrl);
						ctrl.refreshData()
						.then(function(response){
							_requireData(ctrl);
						});
					}, interval);
				}
			},
			/*
				停止动实时模式
			*/
			stopRealTimeMode: function(){
				clearTimeout(this.timeTicket);
				this.timeTicket = null;
			},
			// /*
			// 	启动实时模式
			// */
			// startRealTimeMode: function(){
			// 	alert(1);
			// 	this.get("controllers.businessDetail").addRealTimeHook(this, "refreshData");
			// },

			// /*
			// 	停止动实时模式
			// */
			// stopRealTimeMode: function(){
			// 	this.get("controllers.businessDetail").removeRealTimeHook(this, "refreshData");
			// },

			// /*
			// 新增实时模式钩子方法, 子界面需要在实时模式请求时, 同步执行的方法时, 调用该方法.
			// */
			// addRealTimeHook: function(target, method /*, args */) {
			// 	if (!method) {
			// 		method = target;
			// 		target = null;
			// 	}

			// 	if (Ember.typeOf(method) == "string") {
			// 		method = target[method];
			// 	}

			// 	var args = [].slice.call(arguments, 2);

			// 	var isUniq = true;
			// 	this.realTimeCallbacks.forEach(function(obj){
			// 		if(method == obj.method && target == obj.target){
			// 			isUniq = false;
			// 		}
			// 	});

			// 	if(!isUniq){
			// 		return;
			// 	}

			// 	this.realTimeCallbacks.push({
			// 		target: target,
			// 		method: method,
			// 		args: args
			// 	});
			// },

			removeRealTimeHook: function(target, method){
				if (!method) {
					method = target;
					target = null;
				}

				if (Ember.typeOf(method) == "string") {
					method = target[method];
				}

				var index,
					callbacks = this.realTimeCallbacks;
				callbacks.forEach(function(context, i){
					if(context.method == method){
						index = i;
					}
				});
				callbacks.removeObject(callbacks.objectAt(index));
			},

			/*
			自动智能补全性能数据以填充图标, 按每分钟一条数据
				@param {array} performances 性能数组
				@param {nunber} startDate 补全后的目标长度
				@param {date} endDate 结束时间
				@param {string} dateType 时间显示类型{1.今天，2.昨天，3.上周}
			*/
			performancesCompletion: function(performances, startDate, endDate, dateType){
				startDate = new Date(+startDate),
				endDate = new Date(+endDate);

				if(!startDate && !endDate){
					Ember.assert("startDate, 或者endDate参数不是时间");
					return;
				}

				performances = performances||[];

				startDate.setSeconds(0);
				startDate.setMilliseconds(0);
				endDate.setSeconds(0);
				endDate.setMilliseconds(0);

				var performancesMap = {};
				for(var i = performances.length-1 ; i >= 0 ; i--){
					performancesMap[performances[i].timestamp] = performances[i];
					if(dateType){
						performances[i].timestampType = dateType;
					}
				}

				var timestamp = +startDate,
					newPerformances = [];
				for(; timestamp < +endDate ; timestamp += 60000){
					if(!performancesMap[timestamp]){
						newPerformances.push({"timestamp": timestamp});
					}else{
						newPerformances.push(performancesMap[timestamp]);
					}
				}

				return Ember.A(newPerformances);
			},

			actions: {
				toggleIndicatorsConfig: function(){
					this.set("isConfigIndicators", !this.get("isConfigIndicators"));
				},
				complateChoose:function(){
					var div = $(".tradesKeyUri")[0];
					if ("ActiveXObject" in window) {
					    // for IE
					    var r = document.body.createTextRange();
					    r.moveToElementText(div);
					    r.moveEnd("character"); 
					    r.select();
					} else {
					    // For others
					    var s = window.getSelection();
					    var r = document.createRange();
					    r.selectNode(div);
					    s.addRange(r);
					}
				}
				// timeRangesChange: function(timeRange){
				// 	console.log(timeRange.startDate+','+timeRange.endDate);
				// 	this.set("startDate", timeRange.startDate);
				// 	this.set("endDate", timeRange.endDate);
				// 	this.set("pageIndex", 0);
				// 	this.refreshData();
				// }
			}
		});

		APM.ServiceServerNodeserverOverviewController = Controller;

		return Controller;
	}
);	